﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KP_CommonLibrary.KP_Interface;
using KEEPER_BRR_13dotNET.BusinessLogic;
using KP_CommonLibrary;
using KP_CommonLibrary.KP_CommonControls;
using DevComponents.DotNetBar;
using KP_CommonLibrary.KP_ObjectReferences;
using System.Diagnostics;

namespace KEEPER_BRR_13dotNET.Presentation
{
    public partial class FrmMain : KP_CommonLibrary.KP_CommonControls.KP_FormBase01, IMainForm
    {
        KP_Menu kpMenuMain;

        public FrmMain()
        {
            InitializeComponent();

            kpMenuMain = new KP_Menu();
            sTabMain.Visible = sTabMain.Tabs.Count > 0;
            sTabMain.Dock = DockStyle.Fill;
            sTabMain.BringToFront();
            AppContext.MainForm = this;
        }
        public override bool PreProcessMessage(ref Message msg)
        {
            return base.PreProcessMessage(ref msg);
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //return base.ProcessCmdKey(ref msg, keyData);

            if (!base.ProcessCmdKey(ref msg, keyData))
            {
                if (sTabMain.Tabs.Count > 0)
                {
                    if (sTabMain.SelectedPanel != null)
                    {
                        Control c = sTabMain.SelectedPanel.Controls.Count > 0 ? sTabMain.SelectedPanel.Controls[0] : null;
                        if (c is KP_UserControl)
                        {
                            return ((KP_UserControl)c).DispatchCmdKey(ref msg, keyData);
                        }
                        else
                            return false;
                    }
                    else if (sTabMain.SelectedTab != null)
                    {
                        SuperTabItem selectedTab = sTabMain.SelectedTab as SuperTabItem;
                        DevComponents.DotNetBar.SuperTabControlPanel panel = (DevComponents.DotNetBar.SuperTabControlPanel)selectedTab.AttachedControl;
                        Control c = panel.Controls.Count > 0 ? panel.Controls[0] : null;
                        if (c is KP_UserControl)
                        {
                            return ((KP_UserControl)c).DispatchCmdKey(ref msg, keyData);
                        }
                        else
                            return false;
                    }
                    else
                        return false;
                }
            }
            //if (keyData == Keys.Escape)
            //{
            //    Close();
            //    return true;
            //}
            return false;

        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            kpMenuMain.Load_DataTableMenu();

            ////1. Load Menu into TreeView Main
            kpMenuMain.Gen_Treeview(AdvTreeMain);
            AdvTreeMain.ExpandAll();

            ////2. Load Menu into Menu Main
            kpMenuMain.Gen_Menu(this.bMainMenu);

            ////3. Load Menu into Toolstrip Main
            kpMenuMain.Gen_Toolstrip(bMainToolBar);

            tssUser_Name.Text = KP_OUser.User_Name.PadRight(70);
            tssServer.Text = KP_OCnnSql.Server_Name.PadRight(70);
            tssDatabase.Text = KP_OCnnSql.Server_DbName.PadRight(70);
            tssDate.Text = DateTime.Now.ToShortDateString();
            sTabMain.Visible = false;
            sTabMain.Dock = DockStyle.Fill;
           // pictureBox2.Dock = DockStyle.Fill;
            //pictureBox2.Visible = true;

        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (KPMessageBox.Show("Bạn có chắc chắn muốn thoát chương trình ?", "Xác nhận thoát", KPMessageBoxButton.YesNo, KPMessageBoxIcon.Question) == DialogResult.No)
                e.Cancel = true;
            else
                KP_Menu.Exit_App();
        }
        private void sTabMain_TabItemClose(object sender, DevComponents.DotNetBar.SuperTabStripTabItemCloseEventArgs e)
        {
            SuperTabItem tab = e.Tab as SuperTabItem;
            if (tab != null)
                foreach (Control c in tab.AttachedControl.Controls)
                {
                    if (c is KP_UserControl)
                        ((KP_UserControl)c).Close();
                }

            sTabMain.Visible = sTabMain.Tabs.Count > 1;
           // pictureBox2.Visible = sTabMain.Tabs.Count == 0;
        }

        private void sTabMain_TabItemOpen(object sender, SuperTabStripTabItemOpenEventArgs e)
        {
            sTabMain.Visible = sTabMain.Tabs.Count > 0;
            sTabMain.Focus();
           
          //  pictureBox2.Visible = sTabMain.Tabs.Count == 0;
        }
        #region IMainForm Members

        public void PerformCommandClick(object sender, DataRow menuConfig)
        {
            DataRow row = menuConfig;
            if (row["CommandType"].ToString() == "1")
            {
                if (row["CommandName"].ToString() != "" && row["ClassPath"].ToString() != "")
                {
                    Type t = Type.GetType(row["ClassPath"].ToString());
                    try
                    {
                        IRunCommand host = (IRunCommand)Activator.CreateInstance(t);
                        host.RunCommand(sender, row);
                    }
                    catch (Exception ex)
                    {
                        KPMessageBox.Show("Run Command :" + row["CommandName"].ToString() + " fail :"
                            + ex.Message, "Lỗi", KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
                    }
                }
                else if (!row.IsNull("CommandName"))
                    RunCommand(sender, row["CommandName"].ToString());

            }
            if (row["CommandType"].ToString() == "2")
            {
                if (row["ClassPath"].ToString() != "")
                {
                    Type t = Type.GetType(row["ClassPath"].ToString());
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        IKPDataForm frm = (IKPDataForm)Activator.CreateInstance(t);
                        frm.LoadLayout();
                        frm.LoadData();
                        Control c = frm as Control;

                        if (row["CommandName"].ToString() == "Modal")
                        {
                            KP_FormBase01 frmDlg = new KP_FormBase01();
                            frmDlg.Text = row["Title"].ToString().Trim() == "" ? row["Bar_Name"].ToString() : row["Title"].ToString().Trim();
                            frmDlg.AutoSize = true;
                            frmDlg.Size = c.Size;
                            frmDlg.Controls.Add(c);
                            c.Dock = DockStyle.Fill;
                            frmDlg.ShowDialog();
                            frmDlg.Controls.Remove(c);
                            frmDlg.Dispose();

                            frm.Close();
                            c.Dispose();
                        }
                        else
                        {

                            ShowControlInTab(c as KP_UserControl, row["Bar_Name"].ToString());
                            //  c.Focus();
                        }
                    }
                    catch (Exception ex)
                    {
                        KPMessageBox.Show("Create Form :" + row["CommandName"].ToString() + " fail :"
                            + ex.Message, "Lỗi", KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }
                }
            }
            if (row["CommandType"].ToString() == "3")
            {
            }
        }

        public void ShowControlInForm(KP_UserControl c, string title, bool showModal)
        {
            KP_FormBase01 frm = new KP_FormBase01();
            try
            {
                c.LoadLayout();
                c.LoadData();
                c.Dock = DockStyle.Fill;
                frm.Size = c.Size;
                frm.Controls.Add(c);
                frm.Text = title;
                if (showModal)
                {
                    frm.ShowDialog();

                }
                else
                    frm.Show();
            }
            catch (Exception ex)
            {
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                c.Close();
                frm.Dispose();
            }
        }


        public void ShowControlInTab(KP_UserControl c, string title)
        {
            try
            {
                DevComponents.DotNetBar.SuperTabItem newtab = sTabMain.CreateTab(title);
                DevComponents.DotNetBar.SuperTabControlPanel panel = (DevComponents.DotNetBar.SuperTabControlPanel)newtab.AttachedControl;
                c.Dock = DockStyle.Fill;
                panel.Controls.Add(c);
                sTabMain.SelectedTab = newtab;
            }
            catch (Exception ex)
            {
                KPMessageBox.Show(ex.Message, KP_SYS_VARIABLE.M_KEEPER_VER, KPMessageBoxButton.OK, KPMessageBoxIcon.Error);
            }
            finally
            {
                c.Close();
            }
        }

        #endregion

        public void RunCommand(object sender, string commandName)
        {
            if (commandName.ToUpper() == "EXIT")
                Close();
        }
        private void AdvTreeMain_NodeClick(object sender, DevComponents.AdvTree.TreeNodeMouseEventArgs e)
        {
            DataRow row = e.Node.Tag as DataRow;
            if (row == null)
                return;
            else
                PerformCommandClick(sender, row);
        }

        private void AdvTreeMain_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == (int)Keys.F4)
                e.Handled = true;
        }
        [DebuggerNonUserCode]
        [DebuggerStepThrough]
        private void timer1_Tick(object sender, EventArgs e)
        {
            tssDate.Text = DateTime.Now.ToString("dd/MM:yyyy HH:mm:ss");
        }
        
        private void AdvTreeMain_NodeClick_1(object sender, DevComponents.AdvTree.TreeNodeMouseEventArgs e)
        {
            PerformCommandClick(e.Node, e.Node.Tag as DataRow);
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {

        }
    }
    public class HandleCustomCommand : IRunCommand
    {

        #region IRunCommand Members

        public void RunCommand(object sender, object commandData)
        {
            string commandName = (commandData as DataRow)["CommandName"].ToString();
            if (commandName.ToUpper() == "EXIT")
                Application.ExitThread();
            // throw new NotImplementedException();
        }
      

        #endregion
    }
}
